const express = require("express");
const router = express.Router();
const cors = require("cors");
const util = require("util");
const https = require("https");
const url = require("url");
const replacestream = require("replacestream");
const Zlib = require("zlib");

router.use(async function (req, res) {
  let ord_yahoo_url = `https://ord.yahoo.co.jp${req.originalUrl}`;
  let parsed_yahoo_url = url.parse(ord_yahoo_url);
  let req_headers = req.headers;
  let myhost = req_headers['host'];
  req_headers['host'] && (req_headers['host'] = parsed_yahoo_url.host);
  req_headers['referer'] && (req_headers['referer'] = ord_yahoo_url);
  req_headers['origin'] && (req_headers['origin'] = `${parsed_yahoo_url.protocol}//${parsed_yahoo_url.host}`);
  let https_request = https.request({
    host: parsed_yahoo_url.host,
    method: req.method,
    headers: req_headers,
    path: parsed_yahoo_url.path,
    search: parsed_yahoo_url.search
  }, (httpRes) => {
    if (httpRes.headers) {
      for (let h in httpRes.headers) {
        if (h == "location") {
          let loc = httpRes.headers['location'];
          let parsed_loc = url.parse(loc);
          if (parsed_loc.host == "ord.yahoo.co.jp") {
            parsed_loc.host = myhost;
            parsed_loc.hostname = myhost;
            parsed_loc.protocol = "http:";
          }
          if (parsed_loc.host == "search.yahoo.co.jp") {
            parsed_loc.host = 'yahoojp.liblu.me';
            parsed_loc.hostname = 'yahoojp.liblu.me';
            // parsed_loc.protocol = "http:";
          }
          res.setHeader("location", url.format(parsed_loc));
        } else {
          res.setHeader(h, httpRes.headers[h])
        }
      }
    }
    res.status(httpRes.statusCode);
    httpRes.pipe(res);
  });

  https_request.on("error", (err) => {
    res.status(500).send({
      error: `https_request.on("error"`,
      detail: err
    })
  });
  req.pipe(https_request);

});

module.exports = router;